package com.lixia.lxframework.framework.utils.http;

import com.lixia.lxframework.framework.system.ex.BusinessException;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * okhttp3 工具类
 *
 * @Author Mr.wang
 * @Description okhttp3 工具类
 * @Date 2020-04-02
 */
public class OkHttpUtil {
    private static Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    public static OkHttpClient client;

    static {
        client = new OkHttpClient.Builder()
                .readTimeout(60000, TimeUnit.MILLISECONDS)
                .writeTimeout(60000, TimeUnit.MILLISECONDS)
                .connectTimeout(60000, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 上传
     *
     * @param params
     * @param headerParam
     * @param fileMap
     * @param mediaTypeStr
     * @param url
     * @return
     */
    public static final String doUpload(Map<String, String> params, Map<String, String> headerParam,
                                        final Map<String, File> fileMap, String mediaTypeStr, String url) {
        Response response = null;
        try {
            if (StringUtils.isEmpty(url)) {
                throw new BusinessException("未配置文件服务器地址，请检查配置！");
            }
            if (StringUtils.isEmpty(mediaTypeStr)) {
                //设置类型，类型为八位字节流
                mediaTypeStr = "application/octet-stream";
            }
            MediaType mediaType = MediaType.parse(mediaTypeStr);
            MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
            // 添加文件
            for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) {
                File file = fileEntry.getValue();
                RequestBody fileBody = MultipartBody.create(mediaType, file);
                multipartBody.addFormDataPart(fileEntry.getKey(), file.getName(), fileBody);
            }
            // 添加传参
            if (!Objects.isNull(params) && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    multipartBody.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
            MultipartBody requestBody = multipartBody.build();
            Request.Builder builder = getRequestBuilder(headerParam);
            Request request = builder.post(requestBody).url(url).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                assert response.body() != null;
                return new String(response.body().bytes(), StandardCharsets.UTF_8);
            } else {
                logger.error("[{}] having a error，param is:{}", url, params);
                throw new BusinessException("上传到远程服务器失败！失败原因：【" + response.message() + "】");
            }
        } catch (Exception e) {
            throw new BusinessException("上传到远程服务器失败！失败原因：【{}】", e);
        } finally {
            if (!Objects.isNull(response)) {
                response.close();
            }
        }
    }

    private static Request.Builder getRequestBuilder(Map<String, String> headerParam) {
        Request.Builder builder = new Request.Builder();
        if (!Objects.isNull(headerParam) && headerParam.size() > 0) {
            for (Map.Entry<String, String> entry : headerParam.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return builder;
    }

    /**
     * get 请求
     *
     * @param url 请求url地址
     * @return string
     */
    public static String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * get 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public static String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url       请求url地址
     * @param params    请求参数 map
     * @param headerMap 请求头字段
     * @return string
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headerMap) {
        Request request = doGetCommon(url, params, headerMap);
        return execute(request);
    }

    public static Request doGetCommon(String url, Map<String, String> params, Map<String, String> headerMap) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }
        Request.Builder builder = new Request.Builder();
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        logger.info("do get request and url[{}]", sb.toString());
        return builder.url(sb.toString()).build();
    }

    public static byte[] doGetPicture(String url, Map<String, String> params) {
        return doGetPicture(url, params, null);
    }

    public static byte[] doGetPicture(String url, Map<String, String> params, Map<String, String> headerMap) {
        return executeReturnBytes(doGetCommon(url, params, headerMap));
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headerParam) {
        FormBody formBody = addParamToBuilder(params);
        Request.Builder request = buildHeader(headerParam);
        Request buildRequest = request.post(formBody).url(url).build();
        logger.info("do post request and url[{}]", url);
        return execute(buildRequest);
    }

    public static String doPut(String url, Map<String, String> params, Map<String, String> headerParam) {
        FormBody formBody = addParamToBuilder(params);
        Request.Builder request = buildHeader(headerParam);
        Request buildRequest = request.put(formBody).url(url).build();
        logger.info("do put request and url[{}]", url);
        return execute(buildRequest);
    }

    public static String doDelete(String url, Map<String, String> params, Map<String, String> headerParam) {

        FormBody formBody = addParamToBuilder(params);
        Request.Builder request = buildHeader(headerParam);
        Request buildRequest = request.delete(formBody).url(url).build();
        logger.info("do delete request and url[{}]", url);
        return execute(buildRequest);
    }


    public static FormBody addParamToBuilder(Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        return builder.build();
    }

    public static Request.Builder buildHeader(Map<String, String> headerParam) {
        return getRequestBuilder(headerParam);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @return string
     */
    public static String doPostJson(String url, Map<String, String> headermap, String json) {
        logger.info("do post request and url[{}]", url);
        return executePost(url, json, headermap, MEDIA_TYPE_JSON);
    }

    public static String doPutJson(String url, Map<String, String> headermap, String json) {
        logger.info("do put request and url[{}]", url);
        return executePut(url, json, headermap);
    }

    public static String doDeleteJson(String url, Map<String, String> headermap, String json) {
        logger.info("do delete request and url[{}]", url);
        return executeDelete(url, json, headermap);
    }


    public static String executePost(String url, String data, Map<String, String> headerMap, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.post(requestBody).url(url).build();
        return execute(request);
    }

    private static String executePut(String url, String data, Map<String, String> headerMap) {
        RequestBody requestBody = RequestBody.create(OkHttpUtil.MEDIA_TYPE_JSON, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.put(requestBody).url(url).build();
        return execute(request);
    }

    private static String executeDelete(String url, String data, Map<String, String> headerMap) {
        RequestBody requestBody = RequestBody.create(OkHttpUtil.MEDIA_TYPE_JSON, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.delete(requestBody).url(url).build();
        return execute(request);
    }


    private static String execute(Request request) {
        byte[] bytes = executeReturnBytes(request);
        return new String(bytes);
    }

    private static byte[] executeReturnBytes(Request request) {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                assert response.body() != null;
                ResponseBody body = response.body();
                return response.body().bytes();
            } else {
                logger.error("调用远程服务器接口失败！失败原因：【{}|{}】", response.code(), response.message());
                throw new BusinessException("调用远程服务器接口失败！失败原因：【" + response.code() + "|" + response.message() + "】");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException("调用远程服务器接口失败！失败原因：【{}】", e);
        }
    }
}
